package com.example.myweather;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity2 extends AppCompatActivity {

    Button btn_gethttp;
    TextView tv_http;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        btn_gethttp = findViewById(R.id.bu_http);
        tv_http = findViewById(R.id.tv_http);
        btn_gethttp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new HttpTask().execute();
            }
        });
    }
    class HttpTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            String httpUrl = "http://t.weather.sojson.com/api/weather/city/101210403";
            String resultData = "";
            URL url = null;
            try {
                url = new URL(httpUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(urlConnection.getInputStream(), "UTF-8");
                BufferedReader buffer = new BufferedReader(in);
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = buffer.readLine()) != null) {
                    response.append(inputLine);
                }
                buffer.close();
                urlConnection.disconnect();
                // 解析完整的 JSON 数据
                JSONObject jsonData = new JSONObject(response.toString());
                // 获取 forecast 部分的 JSON 数组
                JSONArray forecastArray = jsonData.getJSONObject("data").getJSONArray("forecast");
//                JSONArray cityArray = jsonData.getJSONObject("cityInfo").getJSONArray("city");
                // 遍历 forecast 数组，提取每一天的数据
                for (int i = 0; i < forecastArray.length(); i++) {
                    JSONObject forecast = forecastArray.getJSONObject(i);
                    JSONObject cityInfo = jsonData.getJSONObject("cityInfo");
                    String cityName = cityInfo.getString("city");
                    forecast.put("city",cityName);
                    resultData += "城市：" + cityName +
                            "\n日期：" + forecast.getString("date") +
                            "\n星期：" + forecast.getString("week") +
                            "\n天气类型：" + forecast.getString("type") +
                            "\n风力：" + forecast.getString("fl") +
                            "\n风向：" + forecast.getString("fx") +
                            "\n最高温度：" + forecast.getString("high") +
                            "\n最低温度：" + forecast.getString("low") +
                            "\n日出时间：" + forecast.getString("sunrise") +
                            "\n日落时间：" + forecast.getString("sunset") + "\n\n";
                }
            } catch (Exception e) {
                e.printStackTrace();
                resultData = "获取数据失败：" + e.getMessage();
                Log.e("HttpTask", "Error fetching city data: " + e.getMessage(), e);
            }
            return resultData;
        }

        @Override
        protected void onPostExecute(String resultData) {
            if (!resultData.isEmpty()) {
                tv_http.setText(resultData);
            } else {
                tv_http.setText("抱歉，未能获取数据");
            }
        }
    }

}